//
//  GaoDeMapView.m
//  HanlinWeather
//
//  Created by 任翰林 on 2017/4/5.
//  Copyright © 2017年 任翰林. All rights reserved.
//

#import "GaoDeMapView.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import <Masonry.h>


@interface GaoDeMapView ()<MAMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate>
@property(nonatomic,strong)MAMapView * mamMapView;
@property(nonatomic,strong)UIView * typeView;
@property(nonatomic,strong)UIButton * seletedButton;
@property(nonatomic,strong)NSArray * typeArray;
@property(nonatomic,strong)UISearchBar * searchBar;
@property(nonatomic,strong)AMapSearchAPI * amapSearchAPI;
@property(nonatomic,strong)AMapPOISearchResponse * MapResponse;

@end



@implementation GaoDeMapView


- (instancetype)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame]) {
        
        self.backgroundColor = KRandomColour;
        [self setUpUI];
        //地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
        [AMapServices sharedServices].enableHTTPS = YES;
    }
    return self;
}


- (void)setUpUI
{
    MAMapView * mamapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 22, KScreenWidth, KScreenHeight-22)];
    self.mamMapView = mamapView;
    mamapView.delegate = self;
    [self addSubview:mamapView];
    //是否展示室内地图
    mamapView.showsIndoorMap = YES;
    //设置地图类型
    mamapView.mapType = MAMapTypeStandard;
    //指南针的显示以及位置改变
    mamapView.showsCompass= YES; // 设置成NO表示关闭指南针；YES表示显示指南针
    mamapView.compassOrigin= CGPointMake(mamapView.compassOrigin.x, 32); //设置指南针位置
//
//    //比例尺显示及位置改变
    mamapView.showsScale= YES;  //设置成NO表示不显示比例尺；YES表示显示比例尺
    
    mamapView.scaleOrigin= CGPointMake(mamapView.scaleOrigin.x, 32);  //设置比例尺位置
    
    mamapView.showsUserLocation = YES;
    mamapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;

    
    MAUserLocationRepresentation * User = [MAUserLocationRepresentation new];
////    ///精度圈是否显示，默认YES
//    User.showsAccuracyRing = NO;
////    ///是否显示方向指示(MAUserTrackingModeFollowWithHeading模式开启)。默认为YES
//    User.showsHeadingIndicator = YES;
////    ///精度圈 填充颜色, 默认 kAccuracyCircleDefaultColor
//    User.fillColor = KGreenColour;
////
////    ///精度圈 边线颜色, 默认 kAccuracyCircleDefaultColor
//    User.strokeColor = KRandomColour;
////
////    ///精度圈 边线宽度，默认0
//    User.lineWidth = 2.0;
////
////    ///定位点背景色，不设置默认白色
//    User.locationDotBgColor = [UIColor redColor];
////
////    ///定位点蓝色圆点颜色，不设置默认蓝色
//    User.locationDotFillColor = [UIColor yellowColor];
////
////    ///内部蓝色圆点是否使用律动效果, 默认YES
//    User.enablePulseAnnimation = YES;
//
//    ///定位图标, 与蓝色原点互斥
    User.image = [UIImage imageNamed:@"mineS"];
//
    [mamapView updateUserLocationRepresentation:User];
    
    [self setMapType];
//    [self searchMap];
    
    
    UISearchBar * searchBar = [[UISearchBar alloc]init];
    self.searchBar = searchBar;
    //    UIViewController * subView = [self superview];
    self.searchBar.delegate = self;
    searchBar.placeholder = @"翰林，输入地址地址";
    [self addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(@10);
        make.right.equalTo(@-40);
        make.top.equalTo(@80);
        make.height.equalTo(@40);
    }];
    
    
    
}
//选择地图类型
- (void)setMapType
{
    UIView * typeView = [[UIView alloc]init];
    typeView.backgroundColor = KGreenColour;
    [self addSubview:typeView];
    [typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.offset(10);
        make.bottom.offset(-5);
        make.right.offset(-10);
        make.height.equalTo(@40);
    }];
    self.typeView = typeView;
    NSInteger typeViewWidth = KScreenWidth - 20;
    NSArray * typeArray = @[@"普通",@"卫星",@"夜间",@"导航",@"公交"];
    self.typeArray  =typeArray;
    for (int i = 0; i < 5; i++) {
        UIButton * button = [UIButton new];
        button.tag = 526 + i;
        button.backgroundColor = KLightGray;
        [typeView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.height.equalTo(typeView);
            make.width.equalTo(@(typeViewWidth*0.2));
            make.left.equalTo(@((typeViewWidth*0.2)*i));
            make.centerY.equalTo(typeView);
        }];
//        KLightGray
        if (i == 0) {
            button.selected = YES;
            self.seletedButton = button;
        }
        NSString * typeStr = [typeArray objectAtIndex:i];
        [button setTitle:typeStr forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"LightGrayColor"] forState:UIControlStateSelected];
        [button setBackgroundImage:[UIImage imageNamed:@"WhiteColor"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(typeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
}

//地图类型选择的按钮的点击事件
- (void)typeButtonClick:(UIButton *)sender
{
    self.seletedButton.selected = NO;
    self.seletedButton = sender;
    self.seletedButton.selected = YES;
    NSString * typeStr = [self.typeArray objectAtIndex:sender.tag - 526];
    if ([typeStr isEqualToString:@"普通"]) {
        self.mamMapView.mapType = MAMapTypeStandard;
    }else if ([typeStr isEqualToString:@"卫星"]){
        self.mamMapView.mapType = MAMapTypeSatellite;
    }else if ([typeStr isEqualToString:@"夜间"]){
        self.mamMapView.mapType = MAMapTypeStandardNight;
    }else if ([typeStr isEqualToString:@"导航"]){
        self.mamMapView.mapType = MAMapTypeNavi;
    }else if ([typeStr isEqualToString:@"公交"]){
        self.mamMapView.mapType = MAMapTypeBus;
    }
    
}

//搜索地图
- (void)searchMap:(NSString *)keyWord
{
    
    self.amapSearchAPI = [AMapSearchAPI new];
    self.amapSearchAPI.delegate = self;
    
    AMapPOIKeywordsSearchRequest * request = [AMapPOIKeywordsSearchRequest new];
    
    request.keywords            = keyWord;
    request.city                = @"北京";
//    request.types               = @"高等院校";
    request.requireExtension    = YES;
    
    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
    request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    
    [self.amapSearchAPI AMapPOIIDSearch:request];
    
}


/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        
        return;
    }
    
    self.MapResponse = response;
    //解析response获取POI信息，具体解析见 Demo
    HLLog(@"--------%ld",response.count);
    HLLog(@"--------%@",response.pois);
    HLLog(@"--------%@",response.suggestion);
    NSArray * pois = response.pois;
    AMapPOI * poi = pois.firstObject;
    HLLog(@"--------%@",poi.uid);
    HLLog(@"--------%@",poi.name);
    HLLog(@"--------%@",poi.type);
    HLLog(@"--------%@",poi.typecode);
    HLLog(@"--------%@",poi.location);
    HLLog(@"--------%@",poi.address);
    HLLog(@"--------%@",poi.tel);
    HLLog(@"--------%@",poi.address);
    
    self.gaoDeResultPushBlock(self.MapResponse);
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([self.searchBar.text isEqualToString:@""]) {
        return;
    }

    [self searchMap:self.searchBar.text];
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchBar resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
//    [super viewDidAppear:animated];
    
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(39.989631, 116.481018);
    pointAnnotation.title = @"方恒国际";
    pointAnnotation.subtitle = @"阜通东大街6号";
    
    [self.mamMapView addAnnotation:pointAnnotation];
}


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
